package org.dbstar.scheduler.control.db.dependency;

import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Map;

import org.dbstar.scheduler.beans.JobDependencyItem;
import org.dbstar.scheduler.control.db.MapJsonConfig;
import org.dbstar.scheduler.identifier.DefaultIdentifier;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.NewBeanInstanceStrategy;
import net.sf.json.util.PropertyFilter;


/**
 * 用于转换JobDependencyItem的JsonConfig
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-5-2
 */
public class JobDependencyItemJsonConfig extends JsonConfig {
	public JobDependencyItemJsonConfig() {
		super();
		setRootClass(JobDependencyItem.class);
		setCollectionType(HashSet.class);
		setJsonPropertyFilter(new PropertyFilter() {
			@Override
			public boolean apply(Object source, String name, Object value) {
				return value == null;
			}
		});
		setJavaPropertyFilter(new PropertyFilter() {
			@Override
			public boolean apply(Object source, String name, Object value) {
				return true;
			}
		});
		setNewBeanInstanceStrategy(new NewBeanInstanceStrategy() {
			@SuppressWarnings("unchecked")
			@Override
			public Object newInstance(@SuppressWarnings("rawtypes") Class target, JSONObject source)
					throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException,
					InvocationTargetException {
				if (JobDependencyItem.class == target) {
					JobDependencyItem item = new JobDependencyItem();
					item.setIdentifier(DefaultIdentifier.valueOf(source.getJSONObject("identifier").getString(
							"stringIdentifier")));
					item.setSucceed(source.containsKey("succeed") ? source.getBoolean("succeed") : null);
					item.setParameters(source.containsKey("parameters") ? (Map<String, String>) JSONSerializer.toJava(
							source.getJSONObject("parameters"), new MapJsonConfig()) : null);
					item.setCondition(source.optString("condition", null));
					return item;
				} else {
					return null;
				}
			}
		});
	}
}
